package stu

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"log"
	"math"
	"net/http"
	"strconv"
	"stu.stdx.com/src/config"
)

type VideoTask struct {
	UpdateType    string // 更新类型 1:播放 2:直播回放
	Jjwikiid      string // 课程ID
	TypeId        string // 课程类型
	CurJindu      int    // 当前播放进度
	UserlogId     string // 播放记录ID
	TotalLength   int    // 总时长
	CoursePath    string // 课程路径
	CourseName    string // 课程名称
	WebSocketURL  string // 目标平台的WebSocket地址
	WebSocketPing string // WebSocket心跳地址
	Completed     bool   // 是否完成
}

func (vt *VideoTask) ToSocketMessageValues() string {
	msg := fmt.Sprintf("Update%s: jjwikiid=%s&TypeId=%s&cur_jindu=%v&userlog_id=%s", vt.UpdateType, vt.Jjwikiid, vt.TypeId, vt.CurJindu, vt.UserlogId)
	return msg
}
func (vt *VideoTask) ShowProgressBar(barLength int) {
	progress := float64(vt.CurJindu) / float64(vt.TotalLength)
	// 确保进度不超过100%
	progress = math.Min(progress, 1.0)

	bar := make([]rune, barLength)
	for i := range bar {
		if float64(i)/float64(barLength) < progress {
			bar[i] = '#'
		} else {
			bar[i] = '-'
		}
	}
	// 打印进度条和百分比
	fmt.Printf("\r执行进度：[%s] %.2f%%", string(bar), progress*100)
}
func (vt *VideoTask) formatOutput() string {
	output := fmt.Sprintf("---------START-------\n")
	output += fmt.Sprintf("视频名称：%s\n", vt.CourseName)
	output += fmt.Sprintf("视频类型：%s （1:课程录播 2：直播回放）\n", vt.UpdateType)
	output += fmt.Sprintf("视频地址：%s\n", vt.CoursePath)
	output += fmt.Sprintf("当前进度：%d/%d\n", vt.CurJindu, vt.TotalLength)
	output += fmt.Sprintf("视频总时长: %02d:%02d:%02d\n", vt.TotalLength/3600, (vt.TotalLength%3600)/60, vt.TotalLength%60)
	output += fmt.Sprintf("当前视频ID：%v.\n", vt.Jjwikiid)
	return output
}
func GetVideoInfo(client *http.Client, course StuCourse, cfg config.SocketConfig) (VideoTask, error) {

	resp, err := client.Get(course.Path)
	defer resp.Body.Close()
	if err != nil {
		return VideoTask{}, err
	}
	document, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		log.Fatal(err)
		return VideoTask{}, err
	}
	// 提取 type="hidden" 的 <input> 标签中的 id 和 value 属性
	socketParams := make(map[string]string)
	document.Find("input[type='hidden']").Each(func(index int, item *goquery.Selection) {
		id, idExists := item.Attr("id")
		value, valueExists := item.Attr("value")
		if !idExists {
			return
		}
		if !valueExists {
			return
		}
		socketParams[id] = value
	})
	courseName := ""
	document.Find("h3.block-title div").Each(func(index int, item *goquery.Selection) {
		courseName = item.Text()
	})
	// 提取页面最大进度
	maxJindu, _ := strconv.Atoi(socketParams["max_jindu"])

	updateType := "1"
	if _, ok := socketParams["live_id"]; ok {
		updateType = "2"
	}
	message := VideoTask{
		UpdateType:    updateType,
		CurJindu:      maxJindu,
		CoursePath:    course.Path,
		TotalLength:   course.TotalTime,
		TypeId:        socketParams["TypeId"],
		UserlogId:     socketParams["userlog_id"],
		Jjwikiid:      socketParams["jjwikiid"],
		CourseName:    courseName,
		WebSocketURL:  cfg.Ws,
		WebSocketPing: cfg.Ping,
		Completed:     course.Completed,
	}
	return message, nil
}
